--
-- Author: shunguo.chen
-- Date: 2018-01-09 15:06:46
--
-- CosplayController
--

local CosplayView = import("..views.CosplayView")
local CosplayBookView = import("..views.CosplayBookView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)
	
end

function ClassRef:init()
	self._model = app:getInst("CosplayModel")

    self._isReadyIntoCosplay = false
end

function ClassRef:removeListeners()
	self.super.removeListeners(self)
end

function ClassRef:listEvent()
    return {
    	"onBattleLoadEnd",
    	"onReconnectSuccessed",
        "onMapChanged",
	}
end

function ClassRef:onEvent(eventName, data)
	if eventName == "onBattleLoadEnd" then
		-- 战斗对象加载完成，移除cosplay界面（最后几秒用来加载战斗对象）
		self:closeView()
	elseif eventName == "onReconnectSuccessed" then
        self:onReconnect()
	elseif eventName == "onMapChanged" then
        if self._isReadyIntoCosplay then
            BattleManager:reqTrainingAfterIntoMap()
            self._isReadyIntoCosplay = false
        end
	end
end

-- data = {CosplayInfo, ...}
function ClassRef:openView(data)
	if cc.isDead(self._view) then
		self._view = CosplayView.new(app.mvc.VIEWTYPE_BLUR)
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
		self:addChild(self._view, {notDelete=true})
	end

	-- 匹配界面有可能还在，主动关闭
	app:sendMsg("PvpController", "closeMatchView")
	
	local roles = self._model:getRoles()
	self._view:setData(data, roles)
	self._view:show()
end
function ClassRef:clearView()
	if self._view then 
		self._view = nil
		UIHandler:removePopupUiByKey(CosplayBookView:getViewName())
		self._model:clear()
	end
end

-- 打开cosplay Book
-- data = CosplayRole
function ClassRef:openBookView(data)
	local view = CosplayBookView.new()
	view:onCloseView(function(sender)
    	UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:refresh(data)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
end

function ClassRef:setIsReadyIntoCosplay(isReady)
    self._isReadyIntoCosplay = isReady
end

function ClassRef:getIsReadyIntoCosplay()
    return self._isReadyIntoCosplay or false
end

---------------------------------------------------------------
-- 重连之后，有可能已经完成选择，统一关闭界面
function ClassRef:onReconnect()
	self:closeView()
end

function ClassRef:onUpdateSelect(info)
	if not self:isViewAlive() then return end
	self._view:refresh(info)
end

------------------------------------------------------------
function ClassRef:onOperate(op, param)
	-- print("CosplayController:onOperate op = " .. op)
	if op == "openBook" then
		self:openBookView(param)
	elseif op == "selectRole" then
		self._model:reqSelectRole(param)
	end
end

return ClassRef